import { createReducer } from 'reduxsauce';
import { REHYDRATE } from 'redux-persist/es/constants'

import {
  GET_MY_DOCTOR_SESSTIONS,
  UPDATE_MY_DOCTOR_ACTIVE_SESSION,
  GET_MY_DOCTOR_MESSAGE_NUMBER,
  REDUCED_MY_DOCTOR_MESSAGE_NUMBER
} from '@ACTIONS/myDoctor'
import { ENTER_PATIENT_SESSION } from '@ACTIONS/chat'

const INITIAL_STATE = {
  myDoctors: [],
  loadingMyDoctors: true,
  canLoadMyDoctors: true,
  myDoctorMessageCount: 0,
  refreshing: true,
}

const rehydrate = (state, { payload }) => {
  if (payload && payload.myDoctor) {
    return { ...INITIAL_STATE, ...payload.myDoctor }
  }
  return { ...state }
}

export default createReducer(INITIAL_STATE, {
  [REHYDRATE]: rehydrate,
  [ENTER_PATIENT_SESSION.FAILURE]: (state, { error }) => ({ ...state, error }),
  [ENTER_PATIENT_SESSION.SUCCESS]: (state, { session }) => {
    const myDoctors = [...state.myDoctors]
    const sessionIndex = myDoctors.findIndex(se => se.SessionId === session.SessionId)
    if (sessionIndex !== -1) {
      const thisSession = myDoctors[sessionIndex]
      myDoctors[sessionIndex] = { ...thisSession, NewMessageCounts: 0 }
    }
    return {
      ...state,
      myDoctors
    }
  },
  [GET_MY_DOCTOR_SESSTIONS.FAILURE]: state => ({
    ...state,
    refreshing: false,
    loadingMyDoctors: false
  }),
  [GET_MY_DOCTOR_SESSTIONS.REQUEST]: (state, { payload = {} }) => ({
    ...state,
    refreshing: payload?.skip === 0 ? true : state.refreshing,
    loadingMyDoctors: true
  }),
  [GET_MY_DOCTOR_SESSTIONS.SUCCESS]: (state, { list, skip, canLoadMyDoctors }) => {
    const myDoctors = skip === 0 ? list : [...state.myDoctors, ...list]
    return {
      ...state,
      myDoctors,
      refreshing: false,
      canLoadMyDoctors,
      loadingMyDoctors: false
    }
  },
  [UPDATE_MY_DOCTOR_ACTIVE_SESSION.REQUEST]: (state, { updateSession }) => {
    const myDoctors = [...state.myDoctors]
    const sessionId = updateSession.SessionId
    const newMsgCount = state.currentSessionId === sessionId ? 0 : updateSession.NewMessageCounts
    const sessionIndex = myDoctors.findIndex(se => se.SessionId === sessionId)
    if (sessionIndex !== -1) {
      const session = myDoctors[sessionIndex]
      if (session.last.createdAt > updateSession.last.createdAt) {
        // eslint-disable-next-line no-param-reassign
        updateSession = session
      }
      myDoctors.splice(sessionIndex, 1)
    }

    return {
      ...state,
      myDoctors: [{ ...updateSession, NewMessageCounts: newMsgCount }, ...myDoctors],
    }
  },
  [GET_MY_DOCTOR_MESSAGE_NUMBER.SUCCESS]: (state, { num }) => ({
    ...state,
    myDoctorMessageCount: num,
  }),
  [REDUCED_MY_DOCTOR_MESSAGE_NUMBER.SUCCESS]: (state, { NewMessageCounts }) => ({
    ...state,
    myDoctorMessageCount: Math.max(0, state.myDoctorMessageCount - NewMessageCounts)
  }),
})
